package com.experimental;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.Scanner;

import util.Util;

public class ClientMacro extends Thread {
	private LinkedList<byte[]>	list;
	private OutputStream		os;
	private long				delay;

	public static void main(String[] args)
	{
		long delay = 10;
		new ClientMacro("localhost", 30000, "drawingmacro\\thomas.txt", delay).start();
	}

	public ClientMacro(String host, int port, String macroPath, long delay)
	{
		this.delay = delay;
		list = readMacro(Util.getSystemPath(macroPath));
		Socket s;
		try
		{
			s = new Socket(host, port);
			os = s.getOutputStream();
		} catch (UnknownHostException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void run()
	{

		while (list.size() != 0)
		{
			try
			{
				os.write(list.pop());
				Thread.sleep(delay);
			} catch (IOException e1)
			{
				e1.printStackTrace();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}

	}

	public static LinkedList<byte[]> readMacro(String str)
	{
		FileInputStream fis;
		try
		{
			fis = new FileInputStream(new File(str));
			Scanner scan = new Scanner(fis);
			LinkedList<byte[]> list = new LinkedList<byte[]>();
			while (scan.hasNext())
			{
				String line = scan.nextLine();
				String[] splitLine = line.split("\\s");
				byte[] b = new byte[splitLine.length];
				for (int i = 0; i < splitLine.length; i++)
				{
					b[i] = Byte.parseByte(splitLine[i]);
				}
				list.addLast(b);
			}
			return list;
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		return null;
	}

}
